package h.c.z.designPattern.C02_SingletonPattern;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 多例
 * @author jinsicao
 */
public class ConnectionPool {

	/**
	 * 允许产生的最大连接数
	 */
	private static int maxNumOfConnection = 5;
	
	/**
	 * 存储所有连接信息（编号）的 List
	 */
	private static List<String> connectionInfoList = new ArrayList<String>(maxNumOfConnection);
	
	/**
	 * 存储所有的连接
	 */
	private static List<ConnectionPool> connectionList = new ArrayList<ConnectionPool>();
	
	/**
	 * 当前连接号
	 */
	private static int currentNumOfConnection = 0;
	
	private static int i = 0;
	
	private ConnectionPool () {
		
	}
	
	private ConnectionPool(String info) {
		System.out.println("ConnectionPool#" + i++);
		connectionInfoList.add(info);
	}
	
	// 把所有的连接都产生出来
	static {
		for (int i = 0; i < maxNumOfConnection; i++) {
			connectionList.add(new ConnectionPool(String.format("我是第%s号", i)));
		}
	}
	
	/**
	 * 返回任意一个连接
	 * @return
	 */
	public static ConnectionPool getInstance(String name) {
		Random random = new Random();
		currentNumOfConnection = random.nextInt(maxNumOfConnection);
		
		System.out.println(String.format("ConnectionPool->getInstance#%s#%s", name, currentNumOfConnection));
		return connectionList.get(currentNumOfConnection);
	}
	
	/**
	 * 返回当前连接的信息
	 */
	public String connectionInfo() {
		return connectionInfoList.get(currentNumOfConnection);
	}
}
